package org.springframework.boot.alpacastudydemo.test;
import net.jacobpeterson.alpaca.AlpacaAPI;
import net.jacobpeterson.alpaca.model.util.apitype.BrokerAPIEndpointType;
import net.jacobpeterson.alpaca.openapi.broker.api.AccountsApi;
import net.jacobpeterson.alpaca.openapi.broker.api.CalendarApi;
import net.jacobpeterson.alpaca.openapi.broker.model.AccountExtended;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.util.UUID;
@RestController
public class AlpacaExample {

    @Autowired
    private Config config;
    @GetMapping("/test")
    public String test(){
        try {
            String brokerAPIKey = config.getBrokerAPIKey();
            String brokerAPISecret = config.getBrokerAPISecret();
            final BrokerAPIEndpointType endpointType = BrokerAPIEndpointType.SANDBOX;
            // 创建AlpacaAPI实例[3](@ref)
            AlpacaAPI alpacaAPI = new AlpacaAPI(brokerAPIKey, brokerAPISecret, endpointType);

            // 使用Broker API的accounts()方法获取账户信息[3](@ref)
            // 首先获取账户列表
            AccountsApi accounts = alpacaAPI.broker().accounts();
            CalendarApi calendar = alpacaAPI.broker().calendar();
            LocalDate start = LocalDate.now().minusDays(7);
            LocalDate end = LocalDate.now();
//            EventsApiSSE events = alpacaAPI.broker().events();
            System.out.println("=== 账户日历 ===" + calendar.queryMarketCalendar(start,end,"trading"));

            if (accounts != null) {
                // 通常第一个账户是你要查询的账户
                AccountExtended account = accounts.getAccount(UUID.fromString("85fae14c-0f3c-4789-b8c8-37af34128cec"));

                System.out.println("=== 账户信息 ===");
                System.out.println("账户ID: " + account.getId());
                System.out.println("状态: " + account.getStatus());
                System.out.println("账户号码: " + account.getAccountNumber());
                System.out.println("货币: " + account.getCurrency());
                System.out.println("kyc结果: " + account.getKycResult());
                System.out.println("账户创建时间: " + account.getCreatedAt());
                System.out.println("账户名称: " + account.getAccountName());
            } else {
                System.out.println("未找到账户信息");
            }

            // 使用完毕后关闭OkHttpClient（可选，但推荐）[1,2](@ref)
            alpacaAPI.closeOkHttpClient();
            return "成功获取配置并连接到Alpaca沙箱环境";
        } catch (Exception e) {
            System.err.println("调用Alpaca API时出错: " + e.getMessage());
            e.printStackTrace();
            return "发生错误";
        }
    }
}
